<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-3-26
 * Time: 上午10:43
 * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
 */

function send_comment($businessId, $huifuid,$content,$type, $comment_id = 0){

	$uid = is_login();
	$result = D('Comment')->addComment($uid, $businessId, $huifuid,$content,$type, $comment_id);
	$nickname = query_user('nickname');
	$title = M('activity')->where(array('activityId'=>$businessId))->getField('Title');
    /*
    $uids = get_at_uids($content);
    $uids = array_subtract($uids, array($weibo['uid'], $comment['uid']));
    send_at_message($uids, $weibo_id, $content);
    */
    $data = array( 'first'=>array('value'=>urlencode('标题:'.$title),'color'=>"#743A3A"),
                'keyword1'=>array('value'=>urlencode($nickname),'color'=>'#173177'),
                'keyword2'=>array('value'=>urlencode(date('Y-m-d H:i:s')),'color'=>'#173177'),
                'keyword3'=>array('value'=>urlencode(($content)),'color'=>'#173177'),
               // 'remark'=>array('value'=>urlencode('你说的对啊!'),'color'=>'#FFFFFF'),
            );
     $receiveUid = M('activity')->where(array('activityId'=>$businessId))->getField('sponsorUid');
     $wxmessage = D('WxMessage');
     $res =  $wxmessage->sendMessage('1',$receiveUid,1,$data);



    return $result;

     /*

    $uid = is_login();

    $result = D('WeiboComment')->addComment($uid, $weibo_id, $content, $comment_id);
    //行为日志
    action_log('add_weibo_comment', 'weibo_comment', $result, $uid);
    //通知微博作者
    $weibo =D('Weibo')->getWeiboDetail($weibo_id);
    D('Common/Message')->sendMessage($weibo['uid'], '评论消息' , "评论内容：$content",  'Weibo/Index/weiboDetail',array('id' => $weibo_id), is_login(), 1);
    //通知回复的人
    if ($comment_id) {
        $comment = D('WeiboComment')->getComment($comment_id);
        if ($comment['uid'] != $weibo['uid']) {
            D('Common/Message')->sendMessage($weibo['uid'], '评论消息' ,  "回复内容：$content",  'Weibo/Index/weiboDetail',array('id' => $weibo_id), is_login(), 1);
        }
    }

    $uids = get_at_uids($content);
    $uids = array_subtract($uids, array($weibo['uid'], $comment['uid']));
    send_at_message($uids, $weibo_id, $content);
    return $result;
    */
}




/**
 * send_at_message  发送@消息
 * @param $uids
 * @param $weibo_id
 * @param $content
 * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
 */
function send_at_message($uids, $weibo_id, $content)
{
    $my_username = query_user('nickname');
    foreach ($uids as $uid) {
        $message = '内容：' . $content;
        $title = $my_username . '@了您';
        $fromUid = get_uid();
        $messageType = 1;
        D('Common/Message')->sendMessage($uid, $title, $message, 'Weibo/Index/weiboDetail',array('id' => $weibo_id), $fromUid, $messageType);
    }
}









function parse_topic($content){
    //找出话题
    $topic = get_topic($content);

    //将##替换成链接
    foreach ($topic as $e) {
        $tik = D('Weibo/Topic')->where(array('name' => $e))->find();

        //没有这个话题的时候创建这个话题
        if($tik){
            //D('Weibo/Topic')->add(array('name'=> $e));
            $space_url = U('Weibo/Topic/index',array('topk'=>urlencode($e)));
            $content = str_replace("#$e#", "<a  href=\"$space_url\" target=\"_blank\">#$e# </a>", $content);
        }
    }

    //返回替换的文本
    return $content;
}

function get_topic($content){
    //正则表达式匹配
    $topic_pattern = "/#([^\\#|.]+)#/";
    preg_match_all($topic_pattern, $content, $topics);

    //返回话题列表
    return array_unique($topics[1]);
}

function group_is_exist($group_id){
    $group =  D('Group/Group')->getGroup($group_id);
    return $group ? true : false;
}

function get_group_admin($group_id){
    return D('Group/GroupMember')->getGroupAdmin($group_id);
}

//MOB模块得到用户头衔
function mob_get_head_title($user_id){
    $user_title = D('RankUser')->where(array('status' => 1, 'uid' => $user_id))->select();
    foreach($user_title as &$v){
        $v['title'] = D('Rank')->where(array( 'id' => $v['rank_id']))->find();
        $v['logo']= getThumbImageById($v['title']['logo']);
    }
    //  dump($user_title);exit;
    return $user_title;
}

function parse_weibo_mobile_content($content)
{
    $content = shorten_white_space($content);

    $content = op_t($content,false);

    $content = parse_expression($content);
    //print_r($content);
    $content = newparse_url_mobile_link($content);
    $content['content'] = parseWeiboContent($content['content']);
    $content['content'] = parse_at_mob_users($content['content']);
    $content['content']=parse_br_nb($content['content']);
    $content['wenben'] = parseWeiboContent($content['wenben']);
    $content['wenben'] = parse_at_mob_users($content['wenben']);
    $content['wenben']=parse_br_nb($content['wenben']);
    return $content;
}
function newparse_url_mobile_link($content)
{
    $xincontent['content'] = '';
    $xincontent['wenben'] = '';
    $xincontent['lianjie'][0] = '';
    $i = 0;
    while (strpos($content, 'http://') !== false || strpos($content, 'ftp://') !== false || strpos($content, 'https://') !== false) {
        $http = strpos($content, 'http://');
        $ftp = strpos($content, 'ftp://');
        $https = strpos($content, 'https://');
        if ($http === FALSE) {
            $http = strlen($content);
        }
        if ($ftp === FALSE) {
            $ftp = strlen($content);
        }
        if ($https === FALSE) {
            $https = strlen($content);
        }
        $sousuo = 'http://';
        if ($ftp < $http) {
            $sousuo = 'ftp://';
            if ($https < $ftp) {
                $sousuo = 'https://';
            }
        } else {
            if ($https < $http) {
                $sousuo = 'https://';
            }
        }
        $houmian = stristr($content, $sousuo);
        $qianduan = stristr($content, 'http://', true);
        $xincontent['content'] .= $qianduan;
        $xincontent['wenben'] .= $qianduan;
        $content = $houmian;
        $houmian = stristr($content, '/k1o2n3g4');
        if ($houmian === FALSE) {
            $xincontent['lianjie'][$i] = "<a href=\"$content\" target=\"_blank\"><i class=\"am-icon-link\" style=\"z-index:9999\" title=\"$content\">网页链接</i></a>";
            $xincontent['content'] .= $xincontent['lianjie'][$i];
            $content = '';
            break;
        }
        else{
            $qianduan = stristr($content, '/k1o2n3g4', true);
            $xincontent['lianjie'][$i] = "<a href=\"$qianduan\" target=\"_blank\"><i class=\"am-icon-link\" style=\"z-index:9999\" title=\"$qianduan\">网页链接</i></a>";
            $xincontent['content'] .= $xincontent['lianjie'][$i];
            $content = $houmian;
            $i = $i + 1;
        }



    }
    $xincontent['content'] .= $content;
    $xincontent['wenben'] .= $content;
    return $xincontent;
}
function parse_url_mobile_link($content)
{


    $content = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie",
        "'<a  href=\"$1\" target=\"_blank\"><i class=\"am-icon-link\" title=\"$1\">网页链接</i></a>'", $content
    );
    return $content;
}

function parse_br_nb($content){
    $content = str_replace('/h1a2n3g4', '<br/>',$content);
    $content= str_replace('/k1o2n3g4', '&nbsp;', $content);
    return $content;
}

function parse_at_mob_users($content,$disabel_hight=false)
{
    $content = $content . ' ';
    //找出被AT的用户
    $at_users = get_at_uids($content);
    //将@用户替换成链接
    foreach ($at_users as $e) {
        $user = D('Member')->where(array('uid' => $e))->find();
        if ($user) {
            $query_user = query_user(array('space_mob_url','avatar32'), $user['uid']);

            if(modC('HIGH_LIGHT_AT',1,'Weibo') && !$disabel_hight){
                $content = str_replace("[at:$e]", " <a class='user-at hl ' ucard=\"$user[uid]\" href=\"$query_user[space_mob_url]\"><img class='am-circle' src=\"$query_user[avatar32]\">@$query_user[nickname] </a> ", $content);
            }else{
                $content = str_replace("[at:$e]", " <a ucard=\"$user[uid]\" href=\"$query_user[space_url]\">@$query_user[nickname] </a> ", $content);
            }

        }
    }
    //返回替换的文本
    return $content;
}

function check_verify($code, $id = 1){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}




function local_comment_textarea($param=array()){
    $html = '<div class="am-form-group weibo_post_box am-cf" style="padding: 10px"><h6>评论</h6>';
    if (!is_login()) {
        $html.='<div  style=" position: relative; "><div class="am-g am-text-center" style="position: absolute;padding: 50px;"><span> 请先<a href="'.U('Mob/member/index').'">登录</a>
        后再评论</span></div> <textarea  rows="5"   disabled style="height: 8em; width: 100%;"></textarea></div>';
    }else{
        $html.='<textarea class="content" rows="5" id="comment_content_text"   style="height: 8em; width: 100%;"></textarea>';
    }

    $html.=' <div class="am-cf" style="margin: 5px 0px"><a href="javascript:" data-url=" '.U('Core/Expression/getSmile').'" onclick="insertFace($(this))"><img src="'.C('TMPL_PARSE_STRING.__IMG__').'/bq.png"></a> </div><div id="emot_content" class="emot_content"></div>';
    $html .= '<p>';
    $html.= '<button style="float: right"   data-role="do_local_comment" data-url="'.U('mob/base/addLocalComment',array('uid'=>$param['uid'],'count_model'=>$param['count_model'],'count_field'=>$param['count_field'])).'" data-this-url="'.$param['this_url'].'" data-path="'.$param['path'].'"  data-extra="'.http_build_query($param['extra']).'"  type="button"  class="am-btn-warning am-btn am-btn-block am-round ">提交</button>';
    $html .= '</p></div>';
    return $html;

}



function get_local_comment_list($path,$page=1){
    $html = '<div class="localcomment_list">';
    $html .=  A('Mob/Base')->getLocalCommentList($path,$page);
    $html .='</div>';
    $html.='    <div class="am-list-news-ft"><a class=" am-btn am-btn-secondary am-btn-block" href="javascript:" data-role="show_more_localcomment" data-path="'.$path.'">查看更多 &raquo;</a> </div>';
    return $html;
}


function mobU($url = '', $vars = '', $suffix = true, $domain = false){
    $url = preg_replace("/(?<=#)[\s\S]*$/","",$url);
    $link =  require('./Application/Mob/Conf/router.php');
    $url_mob = $link['router'][$url];
    return U($url_mob, $vars , $suffix, $domain);
}
//群组
function limit_picture_count($content){
    return   D('ContentHandler')->limitPicture($content,modC('GROUP_POST_IMG_COUNT',10,'GROUP'));
}

function get_group_name($group_id){
    $group =  D('Group')->getGroup($group_id);
    return $group['title'];
}
//群组
function is_joined($group_id)
{
    return D('Group/GroupMember')->getIsJoin(is_login(),$group_id);
}
function get_reply_admin($reply_id){
    return get_admin_ids($reply_id,2,1);
}
/**
 * 权限检测时获取要排除的uids(群创建者、群组管理员、自己)
 * @param int $id
 * @param int $type
 * @param int $with_self 是否包含记录的uid
 * @return array|int|mixed
 * @author 郑钟良<zzl@ourstu.com>
 */
function get_admin_ids($id=0,$type=0,$with_self=1)
{
    $uid=0;
    switch($type){
        case '1'://根据贴子楼中楼回复id查询排除者id
            $lzl_reply=M('GroupLzlReply')->find($id);
            $uid=$lzl_reply['uid'];
            $post_id=$lzl_reply['post_id'];
            break;
        case '2'://根据贴子回复id查询排除者id
            $reply = M('GroupPostReply')->find($id);
            $uid=$reply['uid'];
            $post_id=$reply['post_id'];
            break;
        case '3'://根据贴子id查询排除者id
            $post_id=$id;
            break;
        case '4'://根据群组 id查询排除者id
            $group_id=$id;
            break;
        default:
            return -1;
    }
    if($post_id){
        $post=M('GroupPost')->where(array('id' => $post_id, 'status' => 1))->find();
        $group_id=$post['group_id'];
        if(!$uid){
            $uid=$post['uid'];
        }
    }
    $expect_ids=D('GroupMember')->getGroupAdmin($group_id);
    $group=M('Group')->find($group_id);
    if($uid&&$with_self&&$uid!=$group['uid']){
        $expect_ids[]=$group['uid'];
    }
    return $expect_ids;
}

function get_lzl_admin($lzl_id){
    return get_admin_ids($lzl_id,1,1);
}
function post_is_exist($post_id){
    $post =  D('GroupPost')->getPost($post_id);
    return $post ? true : false;
}
function get_post_admin($post_id){
    return get_admin_ids($post_id,3,1);
}
function get_group_creator($group_id){
    $group = D('Group')->getGroup($group_id);
    return $group['uid'];
}

//分类信息
function CheckCanRead($uid, $info_id)
{
    $info = D('cat_info')->find($info_id);
    return CheckCanReadEntity($uid, $info['entity_id']);
}
function CheckCanReadEntity($uid, $entity_id)
{
    return CheckCan($uid, $entity_id, 'can_read_gid');
}
function CheckCan($uid, $entity_id, $can_type)
{
    if(is_administrator())
        return true;
    $entity = D('cat_entity')->find($entity_id);
    if(trim($entity[$can_type])=='' || intval($entity[$can_type])==0){
        return true;
    }
    $gids = explode(',', $entity[$can_type]);

    $group_result = D('auth_group_access')->field('group_id')->where(array('uid' => $uid))->select();

    $user_groups = getSubByKey($group_result, 'group_id');
    $has = array_intersect($gids, $user_groups);

    if (count($has))
        return true;
    else
        return false;

}

function CheckCanPostEntity($uid, $entity_id)
{

    return CheckCan($uid, $entity_id, 'can_post_gid');
}
/**解析选项
 * @param $option_str
 * @return array
 * @auth 陈一枭
 */
function parseOption($option_str)
{
    $option_str = str_replace("\r", '', $option_str);
    $values = explode("\n", $option_str);
    foreach ($values as &$v) {
        $v = trim($v);
    }
    return $values;
}

//微店
function encodeGallary($gallary)
{
    foreach ($gallary as $g) {
        $gallary_array[] = array('id' => $g);
    }

    return json_encode($gallary_array);

}

function getTaskSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'T'.date('YmdHis').$num;

}
function getDateTime($day='')
{
 if(empty($day))
 {
  return date('Y-m-d H:i:s');
 }else
 {
return (date("Y-m-d H:i:s",strtotime("+".$day." day")));

 }

}
function getRedPackSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'R'.date('YmdHis').$num;

}

function getOrderSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'O'.date('YmdHis').$num;

}
function getJobsSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

    return 'J'.date('YmdHis').$num;

}




function getAcceptSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'A'.date('YmdHis').$num;

}

function getNoticeSerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'N'.date('YmdHis').$num;

}




function getActivitySerialno($length=18)
{
$count=$length-14;
$num ;
for($i=0;$i<$count;$i++)
{
$num.=rand(0,9);
}

return 'A'.date('YmdHis').$num;

}


function filter_array($array)
{
 if(!is_array($array))  //判断如果参数不是数组的话，直接返回
 {
 return null;    //返回结果为空
 }
 static $data = array();

 foreach($array as $key =>$value)
 {
 	if($value==null) //判断一下当前数组值是否为空，如果为空则直接过滤掉。
 	{
 	constant;  //跳出当前循环
 	}
 	else
 	{
    $data[$key]=$value;
 	}


 }
 return $data;

}


function getserial($leng=6)
{
  $rend;


 for($count=1;$count<=$leng;$count++)
 {
 $rend.=rand(0,9);
 }

 return $rend;
}




function ismobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    //此条摘自TPM智能切换模板引擎，适合TPM开发
    if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
        return true;
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
        );
        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
 }


function getSerialno($length=18)
{
$count=$length-14;

$num = getserial($count);

return date('YmdHis').$num;

}
function getPaySerialno($length=18)
{
 return 'P'. getSerialno();

}
/**
   * 下载文件
   *
   * @param $url
   *  下载文件的地址
   * @param $saveName
   *  保存文件名称
   * @param $path
   *  保存路径
   * @return boolean true = 成功 false=失败
   */
 function put_file_from_url_content($url, $saveName, $path) {
    // 设置运行时间为无限制
    set_time_limit ( 0 );

    $url = trim ( $url );
    $curl = curl_init ();
    // 设置你需要抓取的URL
    curl_setopt ( $curl, CURLOPT_URL, $url );
    // 设置header
    curl_setopt ( $curl, CURLOPT_HEADER, 0 );
    // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    // 运行cURL，请求网页
    $file = curl_exec ( $curl );
    // 关闭URL请求
    curl_close ( $curl );
    // 将文件写入获得的数据
    $filename = $path . $saveName;
    $write = @fopen ( $filename, "w" );
    if ($write == false) {
        return true;
    }
    if (fwrite ( $write, $file ) == false) {
        return false;
    }
    if (fclose ( $write ) == false) {
        return false;
    }
    else
    {
    return true;
    }
 }
    /**
   * 剪切图片大小
   *
   * @param $ImaName
   *  源图片文件名称
   * @param $TargetMaxPx
   *  大小
   * @param $TargetPath
   *  保存路径
   * @param $Quality
   *  质量值
   * @return boolean true = 成功 false=失败
   */



	 function ImageResize($ImaName,$TargetMaxPx, $TargetPath, $Quality = 95)
	{
		if ($ImaName) {
	       $ImageSize = getimagesize($ImaName);
			$MinImagePx = min($ImageSize[0], $ImageSize[1]);
			//chmod($TargetPath, 0777);
			$Percent = 1.0;
			if($ImageSize[0] > $ImageSize[1]){
				$SourceX = round(($ImageSize[0] - $ImageSize[1])/2);
				$SourceY = 0;
				$Percent = 1.0 * $TargetMaxPx / $ImageSize[0];
			}else{
				$SourceX = 0;
				$SourceY = round(($ImageSize[1] - $ImageSize[0])/2);
				$Percent = 1.0 * $TargetMaxPx / $ImageSize[1];
			}

	    switch ($ImageSize[2]) {
					case 1: //GIF
						$ImageObject = imagecreatefromgif($ImaName);
						break;
					case 2: //JPEG
						$ImageObject = imagecreatefromjpeg($ImaName);
						break;
					case 3: //PNG
						$ImageObject = imagecreatefrompng($ImaName);
						break;
					default:
						break;
				}



			//一个正方形图像，用来临时保存原图像中间部分
			$TempImageData = imagecreatetruecolor($MinImagePx, $MinImagePx);
			//将原图像中间部分拷贝到正方形中
			imagecopy($TempImageData, $ImageObject, 0, 0, $SourceX, $SourceY, $MinImagePx, $MinImagePx);
			//目标图像
			$TargetImageData = imagecreatetruecolor($TargetMaxPx, $TargetMaxPx);
			$Background      = imagecolorallocate($TargetImageData, 255, 255, 255);
			imagefill($TargetImageData, 0, 0, $Background);
			//缩放
			imagecopyresampled($TargetImageData, $TempImageData, 0, 0, 0, 0, $TargetMaxPx, $TargetMaxPx, $MinImagePx, $MinImagePx);
			return imagejpeg($TargetImageData, $TargetPath, $Quality);
		} else {
			return false;
		}
	}

	 function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }


function contentsubstr($str,$length=20,$separation='....')
{

$str = rehtml($str);
if(mb_strlen($str,'utf-8')>=$length)
{

$str = mb_substr($str,0,$length,'utf-8').$separation;
}

return $str;

}
 function get_WxOpenId()
{
 if(is_weixin())  //判断是否为通过微信浏览器登录
 {
 $uid = get_uid();    //取登录UID
  $wxUser = D('WxUser');  //实例化微信用户模型
 if($uid==0)        //如果ID为0的话，代表没有登录。
 {

 $openId = $wxUser->getWxopenid();   //调用getopenid接口

 }else
 {
 $openId =  $wxUser->queryWxUserOpenId($uid);

 }
 return $openId;


 }else
 {
 return null;
 }


}

 function unique_rand($probability, $num) {
$min=1;
$max=100/$probability*10;
$count = 0;
$return = array();
while ($count < $num) {
if($count==0)
{
$return[]= mt_rand($min, 5);

}else
{
$return[] = mt_rand($min, $max);
}


$return = array_flip(array_flip($return));
$count = count($return);
}
shuffle($return);
return $return;
}

function formatDate($date)
{
$str = strtotime($date);
return (date("n月j日 H:i",$str));

}


function cache_get($name,$type='Memcache')
{

 return D('Cache')->get($name,$type);



}
function cache_set($name,$value,$type='Memcache',$time=3600)
{
 D('Cache')->set($name,$value,$type,$time);

}
 function cache_del($name,$type='Memcache')
{
D('Cache')->delete($name,$type='Memcache');

}

function rehtml($data){
    $data = preg_replace("/<em([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/em>/i", "", $data);
    $data = preg_replace("/<img([^>]+)?>/i", "", $data);
    $data = preg_replace("/<div([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/div>/i", "", $data);
    $data = preg_replace("/<table([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/table>/i", "", $data);
    $data = preg_replace("/<tr([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/tr>/i", "", $data);
    $data = preg_replace("/<td([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/td>/i", "", $data);
    $data = preg_replace("/<tbody([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/tbody>/i", "", $data);
    $data = preg_replace("/<strong([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/strong>/i", "", $data);
    $data = preg_replace("/<p([^>]+)?>/i", "<p>", $data);
    $data = preg_replace("/<span([^>]+)?>/i", "<p>", $data);
    $data = preg_replace("/<\/span>/i", "</p>", $data);
    $data = preg_replace("/<h1([^>]+)?>.*<\/h1>/i", "", $data);
    $data = preg_replace("/<h2([^>]+)?>.*<\/h2>/i", "", $data);
    $data = preg_replace("/<font([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/font>/i", "", $data);
    $data = preg_replace("/<center([^>]+)?>/i", "", $data);
    $data = preg_replace("/<\/center>/i", "", $data);
    $data = preg_replace("/<b ([^>]+)?>.*?<\/b>/i", "", $data);
    $data = preg_replace("/<a [^>]*>.*?<\/a>/i", "", $data);
    $data = preg_replace("/<a [^>]*>.*?<\/a>/i", "", $data);
    $data = preg_replace("/<\/div>/i", "", $data);
    $data = preg_replace("/[<\/div>]/i", "", $data);
     $data = preg_replace("/[\\\]/i", "", $data);



    return $data;
}


 function GetDistance($lat1, $lng1, $lat2, $lng2)
{
	$EARTH_RADIUS = 6378.137;
	$radLat1 = rad($lat1);
	//echo $radLat1;
	$radLat2 = rad($lat2);
	$a = $radLat1 - $radLat2;
	$b = rad($lng1) - rad($lng2);
	$s = 2 * asin(sqrt(pow(sin($a/2),2) +
	cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
	$s = $s *$EARTH_RADIUS;
	$s = round($s * 10000) / 10000;
	return $s*1000;
}


function verifyDistance($lat1, $lng1, $lat2, $lng2,$distance=10)
{
	$aDistance = GetDistance($lat1, $lng1, $lat2, $lng2);

	if($aDistance<$distance)
	{
	return true;
	}else
	{
	return false;
	}

}
function rad($d)
  {
	return $d * 3.1415926535898 / 180.0;
  }



